package com.lagou.subjectfour;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器
 */
public class SubjectFourMain {
    public static void main(String[] args) {
        //定义基本信息
        ServerSocket ss = null;
        Socket s = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            //创建服务定义端口
            ss = new ServerSocket(8888);
            System.out.println("服务已开启！");
            while (true) {
                //等待获取客户端信息
                s = ss.accept();
                ois = new ObjectInputStream(s.getInputStream());
                oos = new ObjectOutputStream(s.getOutputStream());

                //获取信息
                Object obj = ois.readObject();
                UserMessage userMessage = null;
                //判断客户端传过来是不是UserMessage类的信息
                if (obj instanceof UserMessage) {
                    userMessage = (UserMessage) obj;
                    //检查UserMessage类的内容
                    CheckUserMessage(userMessage);
                    System.out.println(userMessage);
                }
                //返回信息
                if (userMessage != null)
                    oos.writeObject(userMessage);
                else
                    oos.writeObject("输入的格式错误！");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //region 关闭一系列处理
            if (null == ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null == oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null == s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null == ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //endregion
        }

    }

    /**
     * 判断账号密码修改 type
     *
     * @param userMessage
     */
    public static void CheckUserMessage(UserMessage userMessage) {
        User user = userMessage.getUser();
        if ("admin".equals(user.getUserName()) && "123456".equals(user.getPassword()))
            userMessage.setType("success");
    }
}
